<?php

include_once ENTITIES."rota.php";

include_once MODELS."rota.php";

class RotaController {
    
    private $modelRota = null;
    
    public function __construct() {
        $this->modelRota = new RotaModel();
    }
    
    function addRota(Rota $rota = null){
        
        if(is_null($rota)){
            $rota = new Rota();
            $this->linkRota($rota);
        }
        
        global $config;
        
        $hasIds = $config->filter("for-update-id");
        
        if(!empty($hasIds)) {
            $rota->id = $hasIds;
            $res = $this->modelRota->update($rota);
        } else {
            $res = $this->modelRota->insert($rota);
        }
        if($res){
            $config->successInFunction();
        } else {
            $config->failInFunction($this->modelRota->handleError());
        }
        
        $config->redirect("?op=cad-rota");
        
    }
    
    public function linkRota(Rota &$rota){
        global $config;
        $rota->nome =  mb_strtoupper($config->filter("nome"), 'UTF-8');
        $rota->regiao = (int) $config->filter("regiao");
    }
    
    function removeRota(){
        global $config;
        $id_rota = $config->filter("rota");
        if(isset($id_rota)){
            if($this->modelRota->delete($id_rota)){
                $config->successInFunction();
            } else {
                $config->failInFunction($this->modelRota->handleError());
            }    
        } else {
            $config->failInFunction("Rota não informada");
        }
        $config->redirect("?op=cad-rota");
    }
    
    function getAllRotas($foreign_values = false, $byLoja = false){
        $condition = null;
        if($byLoja){
            $condition = RegiaoModel::TABLE.".".RegiaoModel::LOJA." = $byLoja";
        }
        if($foreign_values){
            return $this->modelRota->superSelect($condition);
        }
        return $this->modelRota->select("*", $condition);
    }
    
    public function getRotasByRegiao($id_regiao){
        $condition = RotaModel::REGIAO." = $id_regiao";
        return $this->modelRota->select("*", $condition);
    }


    function getRotaById($idrota){
        $rota = $this->modelRota->select(" * ", RotaModel::TABLE.".".RotaModel::ID." = ".$idrota);
        if(count($rota)) return $rota[0];
        return new Rota();
    }
    
}
?>
